package com.accompany.fragment.home.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.accompany.R;
import com.accompany.api.bean.OrderDetialBean;
import com.accompany.api.category.OrderDetialCatgory;
import com.accompany.api.presenter.OrderDetialPresenter;
import com.accompany.base.BaseActivity;
import com.accompany.base.BaseBean;
import com.accompany.dialog.RoundKefuDialog;
import com.accompany.fragment.order.activity.OrderDetialsActivity;
import com.accompany.fragment.order.activity.OrderServicectivity;
import com.accompany.main.ConstantStaticUrl;
import com.accompany.utils.HttpNetworkConnectUtils;
import com.accompany.utils.SPUtils;
import com.accompany.utils.TimeUtils;
import com.accompany.utils.ToastUtil;

import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.OnClick;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;
/**
 * 信息说明:
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/3/16 17 ：55
 * 项目名称：yuanban
 */
public class TakeOrdersDetialsActivity extends BaseActivity implements OrderDetialCatgory.View {
    @BindView(R.id.base_title)
    TextView mTitleMsg;
    @BindView(R.id.service_msg)
    TextView mServiceName;
    @BindView(R.id.order_no)
    TextView mOrderNo;
    @BindView(R.id.order_price_title)
    TextView mOrderPrice;
    @BindView(R.id.name)
    TextView mName;
    @BindView(R.id.lxfs)
    TextView mMobile;
    @BindView(R.id.service_day)
    TextView mServiceDay;
    @BindView(R.id.service_keshi)
    TextView mServiceKeshi;
    @BindView(R.id.service_yiyuan)
    TextView mServiceYiyuan;
    @BindView(R.id.service_content)
    TextView getmServiceMsg;
    @BindView(R.id.ordr_gender)
    TextView mOderGender;
    @BindView(R.id.order_age)
    TextView mOrderAge;
    @BindView(R.id.start_service)
    TextView mStartService;
    @BindView(R.id.pay_order)
    TextView mPayMsg;
    private String mToken;
    private long orderId;
    private OrderDetialPresenter mPresenter;
    private String mMobilePhone;
    private boolean isCalling = false;
    private OrderDetialBean baseBean;
    private String startTime;
    @Override
    public int getLayoutId() {
        return R.layout.activity_order_detials;
    }
    @Override
    public void initLayoutView() {

        mToken = (String) SPUtils.get(TakeOrdersDetialsActivity.this, ConstantStaticUrl.mToken, "");
        YCAppBar.setStatusBarColor(TakeOrdersDetialsActivity.this,
                ContextCompat.getColor(TakeOrdersDetialsActivity.this,
                        R.color.base_color));
        mTitleMsg.setText("接单详情");
        orderId = getIntent().getLongExtra("orderId",0);
        mPresenter = new OrderDetialPresenter(this);
        SetPersenter(mPresenter);
        if (!HttpNetworkConnectUtils.isNetworkConnected(TakeOrdersDetialsActivity.this)) {
            ToastUtil.showToastERROR(TakeOrdersDetialsActivity.this, "网络不给力,请稍后重试");
        } else {
            mPresenter.getOrderDetial(mToken, orderId);
        }
    }
    @OnClick({R.id.base_back,R.id.pay_order,R.id.start_service})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.base_back:
                finishWitchAnimation();
                break;
            case R.id.pay_order:
                RoundKefuDialog dialog = new RoundKefuDialog(TakeOrdersDetialsActivity.this);
                dialog.show();
                TextView mobile = dialog.findViewById(R.id.mobile_number);
                TextView title = dialog.findViewById(R.id.tv_title);
                title.setText("联系就诊人");
                mobile.setText(mMobilePhone);
                dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 检查是否获得了权限
                        if (ContextCompat.checkSelfPermission(TakeOrdersDetialsActivity.this,
                                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // 若没有获得授权，申请授权
                            if (ActivityCompat.shouldShowRequestPermissionRationale(TakeOrdersDetialsActivity.this,
                                    Manifest.permission.CALL_PHONE)) {
                                // 如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                                //  如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                                // 如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                                // 弹窗需要解释为何需要该权限，再次请求授权
                                // 帮跳转到该应用的设置界面，让用户手动授权
                                Intent call = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", TakeOrdersDetialsActivity.this.getPackageName(), null);
                                call.setData(uri);
                                startActivity(call);
                            } else {
                                // 不需要解释为何需要该权限，直接请求授权
                                ActivityCompat.requestPermissions(TakeOrdersDetialsActivity.this,
                                        new String[]{Manifest.permission.CALL_PHONE},
                                        0);
                            }
                        } else {
                            // 已经获得授权，可以打电话
                            // 通过intent跳转到拨打电话的界面
                            Intent intent1 = new Intent();
                            intent1.setAction(Intent.ACTION_CALL);
                            Uri phoneNum = Uri.parse("tel:" + mMobilePhone);
                            intent1.setData(phoneNum);
                            startActivity(intent1);
                            isCalling = true;
                        }
                        dialog.dismiss();
                        //打完电话 显示开始服务
                        if(isCalling){
                            mStartService.setVisibility(View.VISIBLE);
                            mPayMsg.setVisibility(View.GONE);
                        }
                    }
                });
                break;
            case R.id.start_service:

//                try {
//                    long currentTime = System.currentTimeMillis();
//                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//                    String times[] = startTime.split(" ");
//                    String str = times[0]+" "+times[1].split("-")[1];
//                    double startNum = TimeUtils.dateDiff(formatter.format(currentTime),startTime.substring(0,startTime.length()-6),"yyyy-MM-dd HH:mm");
//                    double num1 = TimeUtils.dateDiff(formatter.format(currentTime),str,"yyyy-MM-dd HH:mm");
//                    if (startNum -10 > 10){ //大于十分钟不能服务
//                        ToastUtil.showToastINFO(TakeOrdersDetialsActivity.this,"距离开始时间超过10分钟,不能开始服务");
//                    }else if (num1 -10 > 0){//0-10分钟之间可以开始服务
                try {
//                    Bundle bundle = new Bundle();
//                    bundle.putLong("orderId",orderId);
//                    openActivityWitchAnimation(OrderServicectivity.class,bundle);
                    mPresenter.getStartService(mToken,orderId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                    }else if(num1 - 10 < 0){// <0  超时了,说明情况开始服务
//                        ToastUtil.showToastERROR(TakeOrdersDetialsActivity.this,"时间已经超时");
//                    }
//                } catch (Exception e) {
//                    ToastUtil.showToastERROR(TakeOrdersDetialsActivity.this, e.getMessage());
//                }
                break;
        }
    }
    @Override
    public void getOrderDetial(OrderDetialBean baseBean) {
        this.baseBean = baseBean;
        if (baseBean.getCode()==ConstantStaticUrl.SUCCESS_CODE){
            if (baseBean.getData()!=null){
                mServiceName.setText(baseBean.getData().getTitle());
                mOrderNo.setText(baseBean.getData().getOrderNo());
                mOrderPrice.setText("￥ "+String.valueOf(baseBean.getData().getFinalPrice()));
                mName.setText(baseBean.getData().getOrderDTO().getPatientName());
                mMobilePhone = baseBean.getData().getOrderDTO().getPatientPhone();
                mMobile.setText(baseBean.getData().getOrderDTO().getPatientPhone());
                if (!TextUtils.isEmpty(baseBean.getData().getOrderDTO().getPeriodStr())){
                    mServiceDay.setText(baseBean.getData().getOrderDTO().getPeriodStr());
                    startTime = baseBean.getData().getOrderDTO().getPeriodStr();
//                    startTime = baseBean.getData().getOrderDTO().getPeriodStr().substring(0,baseBean.getData().getOrderDTO().getPeriodStr().length()-6);
                }
                mServiceYiyuan.setText(baseBean.getData().getOrderDTO().getHospitalName());
                mServiceKeshi.setText(baseBean.getData().getOrderDTO().getOfficeName());
                getmServiceMsg.setText(baseBean.getData().getOrderDTO().getRemark());
                if (baseBean.getData().getOrderDTO().getPatientSex().equals("0")){
                    mOderGender.setText("女");
                }else if (baseBean.getData().getOrderDTO().getPatientSex().equals("1")){
                    mOderGender.setText("男");
                }
                mOrderAge.setText(baseBean.getData().getOrderDTO().getPatientAge());
            }
        }else {
            ToastUtil.showToastERROR(TakeOrdersDetialsActivity.this,baseBean.getMsg());
        }
    }

    @Override
    public void getStartService(BaseBean baseBean) {
        if(baseBean.getCode()==ConstantStaticUrl.SUCCESS_CODE){
            Bundle bundle  = new Bundle();
            bundle.putLong("orderId",orderId);
            openActivityWitchAnimation(OrderServicectivity.class,bundle);
            finish();
        }else {
            ToastUtil.showToastINFO(TakeOrdersDetialsActivity.this,baseBean.getMsg());
        }

    }

    @Override
    public void getCompleteOrder(BaseBean bean) {

    }

    @Override
    public void SetPersenter(Object persenter) {

    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {

    }
}
